const gm = require('gm');
const path = require('path');
const exec = require('child_process').exec;
const dir_out = './out';

//压缩 https://pngquant.org/
function compressImg(file, quality) {
    let cmd = `.${path.sep}exec${path.sep}pngquant.exe --ext .png --force --verbose 256 ${file}`;
    exec(cmd, function (err, stdout, stderr) {
        if (err) {
            console.error('compress error ' + file + ' | ' + err);
        } else {
            console.log('compress done', file)
        }
    })

}


function scaleImg(file, size) {
    console.log(file)
    let output = path.join(dir_out, path.basename(file));

    gm(file).scale(size.w, size.h).write(output, function (err) {
        if (err) {
            console.log(err);
        } else {
            console.log(`${file} done`);
            compressImg(output, 50)
            // //中心点坐标换算为左上
            // offset = [(sourceSize[0] - spriteSize[0]) / 2 + offset[0], (sourceSize[1] - spriteSize[1]) / 2 - offset[1]]
            // let cmd = `image Over ${offset[0]},${offset[1]},${spriteSize[0]},${spriteSize[1]},'${fileName}'`
            // console.log('resize', cmd)
            // gm(parseInt(sourceSize[0]), parseInt(sourceSize[1]), '#000000ff').draw(cmd).write(fileName, err2 => {
            //     if (err2) {
            //         console.log('rewrite error', err2)
            //     } else {
            //         console.log('re write done')
            //     }
            // })
        }
    });

}

module.exports = {
    compressImg: compressImg,
    scaleImg
}
